<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen v-model="showDialog" :title="title">
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter v-if="!props.orderId" :filter-list="filterInfo.list">
              <template v-slot:filter-addRow>
                <el-button @click="addRow">新增行</el-button>
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <page-table
                  ref="table"
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tabIndex="false"
                  :check-box="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-incomeDate="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.incomeDate`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择收入日期',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-date-picker
                        v-model="scope.row.incomeDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择收入日期"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.incomeDate`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-projectCode="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.projectCode`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择项目编码',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input
                        :ref="'batchRef' + scope.$index"
                        class="not-mongolia"
                        placeholder="请选择项目编码"
                        disabled
                        v-model="scope.row.projectCode"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.projectCode`,
                            'tableForm'
                          )
                        "
                      >
                        <template #append>
                          <div
                            class="el-input-search"
                            @click="addPro(scope.row, scope.$index)"
                          >
                            <el-icon style="vertical-align: middle">
                              <MoreFilled />
                            </el-icon>
                          </div>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-tsAssetCode="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.tsAssetCode`"
                      @click.stop=""
                    >
                      <el-input
                        :ref="'batchRef' + scope.$index"
                        class="not-mongolia"
                        placeholder="请输入资产编号"
                        v-model="scope.row.tsAssetCode"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.tsAssetCode`,
                            'tableForm'
                          )
                        "
                      >
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-makeDeptName="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.makeDeptName`"
                      @click.stop=""
                    >
                      <el-input
                        :ref="'batchRef' + scope.$index"
                        class="not-mongolia"
                        placeholder="请选择开单科室"
                        disabled
                        v-model="scope.row.makeDeptName"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.makeDeptName`,
                            'tableForm'
                          )
                        "
                      >
                        <template #append>
                          <div
                            class="el-input-search"
                            @click="
                              addDept(scope.row, scope.$index, 'makeDept')
                            "
                          >
                            <el-icon style="vertical-align: middle">
                              <MoreFilled />
                            </el-icon>
                          </div>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-makeDoctor="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.makeDoctor`"
                      @click.stop=""
                    >
                      <el-input
                        :ref="'batchRef' + scope.$index"
                        class="not-mongolia"
                        placeholder="请输入开单医生"
                        v-model="scope.row.makeDoctor"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.makeDoctor`,
                            'tableForm'
                          )
                        "
                      >
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-executeDeptName="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.executeDeptName`"
                      @click.stop=""
                    >
                      <el-input
                        :ref="'batchRef' + scope.$index"
                        class="not-mongolia"
                        placeholder="请选择执行科室"
                        disabled
                        v-model="scope.row.executeDeptName"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.executeDeptName`,
                            'tableForm'
                          )
                        "
                      >
                        <template #append>
                          <div
                            class="el-input-search"
                            @click="
                              addDept(scope.row, scope.$index, 'executeDept')
                            "
                          >
                            <el-icon style="vertical-align: middle">
                              <MoreFilled />
                            </el-icon>
                          </div>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-executeDoctor="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.executeDoctor`"
                      @click.stop=""
                    >
                      <el-input
                        :ref="'batchRef' + scope.$index"
                        class="not-mongolia"
                        placeholder="请输入执行医生"
                        v-model="scope.row.executeDoctor"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.executeDoctor`,
                            'tableForm'
                          )
                        "
                      >
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-checkTime="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.checkTime`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入检查(治疗)人次',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.checkTime"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.checkTime`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-positiveTime="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.positiveTime`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.positiveTime"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.positiveTime`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-income="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.income`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入收费费用',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.income"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.income`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-powerUp="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.powerUp`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.powerUp"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.powerUp`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 选择项目 -->
    <SelectProduct
      v-if="selectProInfo.visible"
      v-model:showDialog="selectProInfo.visible"
      :query="selectProInfo.query"
      :api="selectProInfo.api"
      :highlightRow="true"
      :check-box="!orderId"
      :fieldList="proFieldList"
      title="可选项目"
      placeholder="编码\名称"
      @callback="callBackPro"
    />
    <!-- 选择部门 -->
    <SelectDept
      v-if="selectDept.visible"
      v-model:show-dialog="selectDept.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDept.query"
      :save-empty="true"
      @callback="callDept"
    />
  </div>
</template>

<script setup>
const SelectProduct = defineAsyncComponent(() =>
  import('@/views/asset/analy/components/SelectProduct')
)
import {
  getAnalysisPlanIncomeDataById,
  postAnalysisPlanIncomeData,
  putAnalysisPlanIncomeData,
  getPlanProjectDetailPage,
  getAnalyMaterialMedicineCostPage,
} from '@/api/asset'
const { proxy } = getCurrentInstance()
const emits = defineEmits()

const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  orderId: {
    type: [Number, String],
  },
})
const selectProInfo = ref({
  visible: false,
  query: {
    keyword: '',
    sort: null,
  },
  row: {},
  api: getPlanProjectDetailPage,
  index: 0,
})
const selectDept = ref({
  visible: false,
  query: {
    status: 1,
    deptAuth: 'id',
  },
  row: {},
  index: 0,
  code: '',
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addRow' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [
    {
      randomNumber: new Date().getTime(),
    },
  ],
  tabIndex: 0,
  selections: [],
  fieldList: [
    {
      label: '收入日期',
      value: 'incomeDate',
      type: 'slot',
    },
    {
      label: '项目编码',
      value: 'projectCode',
      type: 'slot',
    },
    { label: '项目名称', value: 'projectName' },
    { label: '资产编号', value: 'tsAssetCode', type: 'slot' },
    { label: '开单科室', value: 'makeDeptName', type: 'slot' },
    { label: '开单医生', value: 'makeDoctor', type: 'slot' },
    { label: '执行科室', value: 'executeDeptName', type: 'slot' },
    { label: '执行医生', value: 'executeDoctor', type: 'slot' },
    { label: '检查(治疗)人次', value: 'checkTime', type: 'slot' },
    { label: '阳性人次', value: 'positiveTime', type: 'slot' },
    { label: '收入费用', value: 'income', type: 'slot' },
    { label: '开机时长', value: 'powerUp', type: 'slot' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '60',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: !props.orderId,
      },
    ],
  },
})
const proFieldList = ref([
  {
    label: '项目编码',
    value: 'projectCode',
  },
  {
    label: '项目名称',
    value: 'projectName',
  },
  {
    label: '分析方案名称',
    value: 'planName',
  },
  {
    label: '分析方案编码',
    value: 'planNo',
  },
  { label: '分析部门', value: 'deptName' },
])
const deptFieldList = ref([{ label: '开单科室', value: 'makeDeptName' }])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  if (props.orderId) {
    getMain()
  }
})

function getMain() {
  getAnalysisPlanIncomeDataById(props.orderId).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = [res.data]
    }
  })
}
function changeValidate(value, str, ref) {
  setTimeout(() => {
    proxy.$refs[ref].clearValidate(str)
  }, 30)
}
function addPro(row, index) {
  selectProInfo.value.row = row
  selectProInfo.value.index = index
  selectProInfo.value.visible = true
}
function callBackPro(data) {
  data.forEach((item, index) => {
    let newObj = {
      projectCode: item.projectCode,
      projectName: item.projectName,
      planName: item.planName,
      planNo: item.planNo,
      analysisPlanId: item.analysisPlanId,
      projectId: item.projectId,
    }
    if (index === 0) {
      tableInfo.value.data[selectProInfo.value.index] = {
        ...selectProInfo.value.row,
        ...newObj,
      }
    } else {
      tableInfo.value.data.splice(selectProInfo.value.index + index, 0, newObj)
    }
  })
  selectProInfo.value.visible = false
  // const index = selectProInfo.value.index
  // const newObj = {
  //   projectCode: obj.projectCode,
  //   projectName: obj.projectName,
  //   planName: obj.planName,
  //   planNo: obj.planNo,
  //   analysisPlanId: obj.analysisPlanId,
  //   projectId: obj.projectId,
  // }
  // tableInfo.value.data[index] = Object.assign(
  //   tableInfo.value.data[index],
  //   newObj
  // )
  // selectProInfo.value.visible = false
}
function addDept(row, index, code) {
  selectDept.value.row = row
  selectDept.value.index = index
  selectDept.value.code = code
  selectDept.value.visible = true
}
function callDept(obj) {
  const index = selectDept.value.index
  const code = selectDept.value.code
  let newObj = {}
  if (code === 'executeDept') {
    newObj = {
      executeDeptId: obj.id,
      executeDeptName: obj.name,
    }
  } else {
    newObj = {
      makeDeptId: obj.id,
      makeDeptName: obj.name,
    }
  }
  tableInfo.value.data[index] = Object.assign(
    tableInfo.value.data[index],
    newObj
  )
  selectDept.value.visible = false
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//新增行
function addRow() {
  const randomNumber = new Date().getTime()
  tableInfo.value.data.push({
    randomNumber: randomNumber,
  })
}
function removeProduct(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row != selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        const tempData = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
        tableInfo.value.data = tempData
      })
  }
}
// 触发事件
function save() {
  if (!tableInfo.value.data || tableInfo.value.data.length === 0) {
    proxy.$message.warning('请添加收入数据！')
    return
  }
  proxy.$refs.tableForm.validate((valid) => {
    if (valid) {
      const api = props.orderId
        ? putAnalysisPlanIncomeData
        : postAnalysisPlanIncomeData
      const queryData = props.orderId
        ? tableInfo.value.data[0]
        : tableInfo.value.data
      api(queryData).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          proxy.$emit('returnModify', false)
        }
      })
    } else {
      proxy.$message.warning('请按照提示输入正确数据')
    }
  })
}
</script>

<style scoped lang="scss">
.el-input-search {
  width: 100%;
  height: 100%;
}
</style>
